package com.android.cherryboard;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.cherryboard.UI.LoginButton;
import com.android.cherryboard.Utility.Utility;
import com.android.cherryboard.fbclass.BaseDialogListener;
import com.android.cherryboard.fbclass.BaseRequestListener;
import com.android.cherryboard.fbclass.SessionEvents.AuthListener;
import com.android.cherryboard.fbclass.SessionEvents.LogoutListener;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.R;
import com.facebook.android.Util;

public class MainActivity extends Activity implements OnClickListener {

	public static final String APP_ID = "237306236398903";

	private LoginButton mLoginButton;
	private TextView mText;
	private ImageView mUserPic;
	private Handler mHandler;
	ProgressDialog dialog;

	final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
	// final static int PICK_EXISTING_PHOTO_RESULT_CODE = 1;

	String[] permissions = { "offline_access", "publish_stream", "user_photos",
			"publish_checkins", "photo_upload" };

	private String graph_or_fql;

	private Button btnPostStatus;

	private EditText etPostStatus;

	private Button btn_getFriends;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if (APP_ID == null) {
			Util.showAlert(this, "Warning", "Facebook Applicaton ID must be "
					+ "specified before running this example: see FbAPIs.java");
			return;
		}

		setContentView(R.layout.main);
		mHandler = new Handler();

		btn_getFriends = (Button) MainActivity.this
				.findViewById(R.id.btn_getFriends);
		mText = (TextView) MainActivity.this.findViewById(R.id.txt_userstatus);
		mUserPic = (ImageView) MainActivity.this
				.findViewById(R.id.imageView_user_pics);

		btnPostStatus = (Button) MainActivity.this
				.findViewById(R.id.button_post_status);
		etPostStatus = (EditText) MainActivity.this
				.findViewById(R.id.editText_post_status);

	}

	/*
	 * callback after friends are fetched via me/friends or fql query.
	 */
	public class FriendsRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			dialog.dismiss();
			Intent myIntent = new Intent(getApplicationContext(),
					FriendsList.class);
			myIntent.putExtra("API_RESPONSE", response);
			myIntent.putExtra("METHOD", graph_or_fql);
			startActivity(myIntent);
		}

		public void onFacebookError(FacebookError error) {
			dialog.dismiss();
			Toast.makeText(getApplicationContext(),
					"Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button_post_status:
			String statusText = etPostStatus.getText().toString();

			if (isInputValid(statusText)) {

				Bundle params = new Bundle();
				params.putString("caption", getString(R.string.app_name));
				params.putString("description", statusText);

				params.putString("picture", Utility.HACK_ICON_URL);
				params.putString("name", "Hello share your ideas");

				Utility.mFacebook.dialog(MainActivity.this, "feed", params,
						new UpdateStatusListener());
				String access_token = Utility.mFacebook.getAccessToken();
				System.out.println(access_token);

			}

			break;
		case R.id.btn_getFriends:

			if (!Utility.mFacebook.isSessionValid()) {
				Util.showAlert(this, "Warning", "You must first log in.");
			} else {
				dialog = ProgressDialog.show(MainActivity.this, "",
						getString(R.string.please_wait), true, true);

				graph_or_fql = "fql";
				String query = "select name, current_location, uid, pic_square from user where uid in (select uid2 from friend where uid1=me()) order by name";
				Bundle params = new Bundle();
				params.putString("method", "fql.query");
				params.putString("query", query);
				Utility.mAsyncRunner.request(null, params,
						new FriendsRequestListener());
				/*
				 * new AlertDialog.Builder(this)
				 * .setTitle(R.string.Graph_FQL_title)
				 * .setMessage(R.string.Graph_FQL_msg)
				 * .setPositiveButton(R.string.graph_button, new
				 * DialogInterface.OnClickListener() {
				 * 
				 * @Override public void onClick(DialogInterface dialog, int
				 * which) { graph_or_fql = "graph"; Bundle params = new
				 * Bundle(); params.putString("fields",
				 * "name, picture, location");
				 * Utility.mAsyncRunner.request("me/friends", params, new
				 * FriendsRequestListener()); }
				 * 
				 * }) .setNegativeButton(R.string.fql_button, new
				 * DialogInterface.OnClickListener() {
				 * 
				 * @Override public void onClick(DialogInterface dialog, int
				 * which) { graph_or_fql = "fql"; String query =
				 * "select name, current_location, uid, pic_square from user where uid in (select uid2 from friend where uid1=me()) order by name"
				 * ; Bundle params = new Bundle(); params.putString("method",
				 * "fql.query"); params.putString("query", query);
				 * Utility.mAsyncRunner.request(null, params, new
				 * FriendsRequestListener()); }
				 * 
				 * }).setOnCancelListener(new DialogInterface.OnCancelListener()
				 * {
				 * 
				 * @Override public void onCancel(DialogInterface d) {
				 * dialog.dismiss(); } }).show();
				 */
			}

			break;
		default:
			break;
		}

	}

	private boolean isInputValid(String statusText) {
		// TODO Auto-
		// TODO Auto-generated method stub
		if (statusText.trim().length() > 1) {

			return true;
		} else {
			// Shake animation

			Animation animation = AnimationUtils.loadAnimation(
					MainActivity.this, R.anim.shake);
			etPostStatus.startAnimation(animation);

			return false;
		}

	}

	/*
	 * callback for the feed dialog which updates the profile status
	 */
	public class UpdateStatusListener extends BaseDialogListener {
		@Override
		public void onComplete(Bundle values) {
			final String postId = values.getString("post_id");
			if (postId != null) {
				/*
				 * new UpdateStatusResultDialog(AppMainActivity.this,
				 * "Update Status executed", values) .show();
				 */
				Toast.makeText(MainActivity.this, "Update Status executed",
						Toast.LENGTH_LONG).show();
			} else {
				Toast toast = Toast.makeText(getApplicationContext(),
						"No wall post made", Toast.LENGTH_SHORT);
				toast.show();
			}
		}

		@Override
		public void onFacebookError(FacebookError error) {
			Toast.makeText(getApplicationContext(),
					"Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT)
					.show();
		}

		@Override
		public void onCancel() {
			Toast toast = Toast.makeText(getApplicationContext(),
					"Update status cancelled", Toast.LENGTH_SHORT);
			toast.show();
		}
	}

}
